package main

//go get github.com/yuin/gopher-lua
import (
	"MqttCloudProtocolServer/publiclib/define"
	"MqttCloudProtocolServer/publiclib/helplib"
	"MqttCloudProtocolServer/publiclib/logiclib"
	"strings"

	"flag"
	"fmt"

	"github.com/chai2010/winsvc"
	"github.com/wonderivan/logger"

	"os"
	"os/exec"
	"path/filepath"
	"time"
)

//服务名称：EmqxService
//显示名称：Emqx守护进程
//描述：启动Emqx服务器
var (
	appPath              string
	flagServiceName      = flag.String("service-name", "EmqxService", "Set service name")
	flagServiceDesc      = flag.String("service-desc", "Emqx守护进程", "Set service description")
	flagServiceInstall   = flag.Bool("service-install", false, "Install service")
	flagServiceUninstall = flag.Bool("service-remove", false, "Remove service")
	flagServiceStart     = flag.Bool("service-start", false, "Start service")
	flagServiceStop      = flag.Bool("service-stop", false, "Stop service")
	flagChildProcess     = flag.Bool("child-process", false, "Child Process")
	isrunning            bool
	dir                  string
)

func init() {
	var err error
	if appPath, err = winsvc.GetAppPath(); err != nil {
		logger.Fatal(err)
	}
	logger.Info(appPath)
	if err := os.Chdir(filepath.Dir(appPath)); err != nil {
		logger.Fatal(err)
	}
	define.InitInternalPath()
	define.CheckIsLog("emqx.log")
	isrunning = true
	dir, _ = filepath.Abs(filepath.Dir(os.Args[0]))
	dir = dir + "/"
}

//StartServer 启动Emqx服务
func StartServer() {
	StopServer()
	if exist, ee := helplib.FileExists(dir + define.EmqxPath + "emqx"); exist {
		if ee != nil {
			println(ee.Error())
		}
	} else {
		if ee != nil {
			println(ee.Error())
		}

	}
	cmd := exec.Command(dir+define.EmqxPath+"emqx", "start")
	//println(dir + define.EmqxPath + "emqx")
	cmd.Stdout = os.Stdout //
	if ee := cmd.Run(); ee != nil {
		logger.Info(ee.Error())
	} //exec: already started

	time.Sleep(time.Second * 15)
	isrunning = true
	//go getCMD("EmqxServer")
	for {
		time.Sleep(time.Second)
		cmdChecking := exec.Command(dir+define.EmqxPath+"emqx", "ping")
		logger.Debug(dir + define.EmqxPath + "emqx ping")
		out, err := cmdChecking.Output()
		if err != nil {
			logger.Info(err.Error())
		}
		logger.Debug(cmdChecking.Run()) //exec: already started
		res := string(out[:])
		logger.Debug(res)
		if err != nil {
			logger.Error(err.Error())
		}
		if !strings.Contains(res, "pong") {
			logger.Debug(res)
			break
			//isrunning = false
		}
	}
	isrunning = false
}

func getCMD(name string) {
	client := new(logiclib.RPCClientManager)
	client.Init()
	client.Start()
	for isrunning {
		cmd := client.GetCommand(&name)
		if cmd != nil {
			if cmd.Name == name {
				switch strings.ToUpper(cmd.Command) {
				case "STOP":
					StopServer()
					break
				}
			}
		}
		time.Sleep(time.Millisecond * 100)
	}
}

//StopServer 停止Emqx服务
func StopServer() {
	cmd := exec.Command(dir+define.EmqxPath+"emqx", "stop")
	out, err := cmd.Output()
	logger.Info(cmd.Run()) //exec: already started
	res := string(out[:])
	logger.Debug(res)
	if err != nil {
		logger.Error(err.Error())
	}
	isrunning = false
}

func mainwin() {
	flag.Parse()
	/*// install service
	if *flagServiceInstall {
		if err := winsvc.InstallService(appPath, *flagServiceName, *flagServiceDesc); err != nil {
			log.Fatalf("installService(%s, %s): %v\n", *flagServiceName, *flagServiceDesc, err)
		}
		fmt.Printf("Done\n")
		return
	}
	// remove service
	if *flagServiceUninstall {
		if err := winsvc.RemoveService(*flagServiceName); err != nil {
			log.Fatalln("removeService:", err)
		}
		fmt.Printf("Done\n")
		return
	}
	// start service
	if *flagServiceStart {
		if err := winsvc.StartService(*flagServiceName); err != nil {
			log.Fatalln("startService:", err)
		}
		fmt.Printf("Done\n")
		return
	}
	// stop service
	if *flagServiceStop {
		if err := winsvc.StopService(*flagServiceName); err != nil {
			log.Fatalln("stopService:", err)
		}
		fmt.Printf("Done\n")
		return
	}
	// run as service
	if !winsvc.InServiceMode() {
		log.Println("main:", "runService")
		if err := winsvc.RunAsService(*flagServiceName, StartServer, StopServer, false); err != nil {
			log.Fatalf("svc.Run: %v\n", err)
		}
		return
	}*/
	// run as normal
	if *flagChildProcess {
		logger.Info("CHILD MODE")
		go getCMD("EmqxServer")
	} else {
		var cmdLine string
		consoleCmd := func() {
			for isrunning && strings.ToUpper(cmdLine) != "EXIT" {
				//logger.Info(cmdLine)
				fmt.Scanln(&cmdLine)
			}
			logger.Info("stop emqx")
			StopServer()
		}
		go consoleCmd()
	}
	logger.Info("start emqx")
	StartServer()
}
